import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

x=np.array([[19,30],[30,40],[39,47],[40,52],[47,50],[50,55],[60,60],[62,65],[73,70],[75,82],[77,85],[90,95],[92,90]])
y=np.array([0,0,0,0,0,0,1,1,1,1,1,1,1])
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)

k_range=range(2,11)
k_error=[]
for k in k_range:
    model=KNeighborsClassifier(n_neighbors=k)
    scores=cross_val_score(model,x,y,cv=5,scoring='accuracy')
    k_error.append(1-scores.mean())

plt.rcParams['font.sans-serif']='Simhei'
plt.plot(k_range,k_error,'r-')
plt.xlabel('k的取值')
plt.ylabel('预测误差率')
plt.show()


#得出结论：当k· 等于5或7时，误差率最低
#k=5与k=7时，分别训练模型
model1=KNeighborsClassifier(5)	#k=5时，建立模型
model1.fit(x_train,y_train)
model2=KNeighborsClassifier(7)	#k=7时，建立模型
model2.fit(x_train,y_train)
#分别使用两个模型预测新样本
pred1=model1.predict([[75,65]])
pred2=model2.predict([[75,65]])
print("k=5时，预测样本的分类结果为",pred1)
print("k=7时，预测样本的分类结果为",pred2)

